<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求与重复请求</title>
</head>

<body>
    <button id="btnSubmit">请求</button>
    <button id="btnCancel">取消请求</button>

    <script>
        const btnSubmit = document.querySelector('#btnSubmit');
        const btnCancel = document.querySelector('#btnCancel');

        let xhr = null;
        // 用于判断是否正在请求，true表示正在请求
        let isPending = false;

        btnSubmit.onclick = function() {
            if (isPending) {
                if (xhr != null) {
                    xhr.abort();
                }
            }
            xhr = new XMLHttpRequest();
            xhr.open('get', 'http://127.0.0.1:9999/cancel');
            xhr.send();
            isPending = true;
            xhr.onreadystatechange = function() {
                if (xhr.readystate === 4) {
                    isPending = false;
                }
            }
        }

        btnCancel.onclick = function() {
            if (xhr != null) {
                // 取消请求
                xhr.abort();
            }

        }
    </script>
</body>

</html>